package util.gui;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;


public class GridPanel extends Panel
{
	private Component[][] cells;
	private int cellNumX,cellNumY;
	private int cellWidth,cellHeight;
	
	public GridPanel(int cellNumX,int cellNumY)
	{
		cells=new Component[cellNumX][cellNumY];
		this.cellNumX=cellNumX;
		this.cellNumY=cellNumY;
	}
	
	public void add(Component child)
	{
		for(int y=0;y<cellNumY;y++)
			for(int x=0;x<cellNumX;x++)
				if(cells[x][y]==null)
				{	
					cells[x][y]=child;
					
					cellWidth=Math.max(cellWidth,child.getWidth());
					cellHeight=Math.max(cellHeight,child.getHeight());
					
					setWidth(LookAndFeel.borderSize+cellNumX*(LookAndFeel.borderSize+cellWidth));
					setHeight(LookAndFeel.borderSize+cellNumY*(LookAndFeel.borderSize+cellHeight));
					
					child.setMaxWidth(cellWidth);
					child.setMaxHeight(cellHeight);
					
					return;
				}
	}
	
	/**
	 * Adds a component to a specific place on the panel.
	 * @param child - component to add.
	 * @param xpos - column to add component.
	 * @param ypos - row to add component.
	 */
	public void add(Component child,int xpos,int ypos)
	{
		cells[xpos][ypos]=child;
		
		cellWidth=Math.max(cellWidth,child.getWidth());
		cellHeight=Math.max(cellHeight,child.getHeight());
		
		setWidth(LookAndFeel.borderSize+cellNumX*(LookAndFeel.borderSize+cellWidth));
		setHeight(LookAndFeel.borderSize+cellNumY*(LookAndFeel.borderSize+cellHeight));
		
		child.setMaxWidth(cellWidth);
		child.setMaxHeight(cellHeight);
	}
	
	public void render(GameContainer gc,Graphics g,int x,int y)
	{
		super.render(gc,g,x,y);
		
		for(int i=0;i<cellNumX;i++)
			for(int j=0;j<cellNumY;j++)
			{
				Component c=cells[i][j];
				if(c!=null)
				{
					int xoff=(cellWidth-c.getWidth())/2;
					int yoff=(cellHeight-c.getHeight())/2;
					c.update(gc,g,x+LookAndFeel.borderSize+i*(cellWidth+LookAndFeel.borderSize)+xoff,
							y+LookAndFeel.borderSize+j*(cellHeight+LookAndFeel.borderSize)+yoff);
				}
			}
	}
}
